const { BrowserView } = require('electron');
const path = require('path');
const fs = require('fs');
/**
 * 视图管理器
 */
class ViewManager {
    constructor(mainWindow) {
        this.mainWindow = mainWindow;
        this.views = new Set();
    }

    resizeView() {
        let view = this.mainWindow.getBrowserView();
        if (view) {
            this.mainWindow.webContents.executeJavaScript('getViewRect()').then(res => {
                view.setBounds(res);
            })
        }
    }

    closeAllPageViews() {
        for (let view of this.views) {
            this.mainWindow.removeBrowserView(view);
            this.views.delete(view);
            view.destroy();
        }
    }

    closePage(windowId) {
        for (let view of this.views) {
            if (view.id == windowId) {
                this.mainWindow.removeBrowserView(view);
                this.views.delete(view);
                view.destroy();
                break;
            }
        }
    }
    changePage(windowId) {
        for (let view of this.views) {
            if (view.id == windowId) {
                this.mainWindow.setBrowserView(view);
                this.mainWindow.webContents.executeJavaScript('getViewRect()').then(res => {
                    view.setBounds(res);
                })
                break;
            } else {
                this.mainWindow.removeBrowserView(view);
            }
        }
    }
    activeWindowId() {
        let view = this.mainWindow.getBrowserView();
        if (view) {
            return view.id;
        }
        else {
            return 0;
        }
    }
    newPage() {
        let view = new BrowserView({
            show: true,
            webPreferences: {
                webSecurity: false,
                nodeIntegration: false,
                preload: path.join(__dirname, 'preload.js')
            }
        });
        view.owner = this.mainWindow;
        this.views.add(view);
        //打开的Web页面要处理 new-window事件,否则不会在标签页上创建
        view.webContents.addListener('new-window', (event, url, ) => {
            let view = this.newPage();
            this.openUrlInPage(url);
            view.owner.webContents.reload();
            //mainWindow.webContents.send('/render/reloadPages');
        });
        view.webContents.loadURL('https://www.baidu.com')
        this.mainWindow.setBrowserView(view);
        this.mainWindow.webContents.executeJavaScript('getViewRect()').then(res => {
            view.setBounds(res);
        })
        //执行注入脚本
        view.webContents.on("did-finish-load", function (e) {
            console.log('did-finish-load.....');
            console.log(this.getURL());
            const js = fs.readFileSync(path.join(__dirname, 'inject.js')).toString();
            
            view.webContents.executeJavaScript(js);
        });

        //主框架页面加载完毕后触发一个事件,通知dva的订阅进行更新
        view.webContents.on('did-frame-finish-load',function(e,isMainFrame ){
            console.log('did-frame-finish-load...');
            console.log(this.getURL());            
            console.log('------------------------------------')
            if(isMainFrame){
                const js = `
                    var ev = new CustomEvent("urlchange", {detail:{windowId:${view.id},url:'${this.getURL()}',title:'${this.getTitle()}'}});
                    document.dispatchEvent(ev);
                `
                //如何通知地址栏更新呢？
                view.owner.webContents.executeJavaScript(js);
            }
        });
        // 
        // view.webContents.on("did-navigate-in-page", function (event, url) {
        //     console.log('did-navigate-in-page.....');    
            
        //     const js = `
        //         var ev = new CustomEvent("urlchange", {detail:{windowId:${view.id},url:'${url}',title:'${this.getTitle()}'}});
        //         document.dispatchEvent(ev);
        //     `
        //     //如何通知地址栏更新呢？
        //     view.owner.webContents.executeJavaScript(js);
            
        // });

        return view;
    }
    async openUrlInPage(url) {
        let view = this.mainWindow.getBrowserView();
        await view.webContents.loadURL(url);
        return view;
    }
    openDev() {
        let view = this.mainWindow.getBrowserView();
        if (view) {
            view.webContents.openDevTools();
        }
        else {
            this.mainWindow.webContents.openDevTools();
        }

    }

    reload() {
        let view = this.mainWindow.getBrowserView();
        if (view) {
            view.webContents.reload();
        }
    }

    goBack() {
        let view = this.mainWindow.getBrowserView();
        if (view) {
            view.webContents.goBack();
        }
    }
    goForward() {
        let view = this.mainWindow.getBrowserView();
        if (view) {
            view.webContents.goForward();
        }
    }
    getPages() {
        let pages = [{
            title: '首页',
            windowId: 0,
            url: ''
        }];
        let activeWindowId = 0;

        let view = this.mainWindow.getBrowserView();
        let urlAddress = '';
        if (view) {
            activeWindowId = view.id;
            urlAddress = view.webContents.getURL();
        }
        for (let view of this.views) {
            pages.push({
                title: view.webContents.getTitle() || '新建标签页',
                windowId: view.id,
                url: view.webContents.getURL()
            })
        }

        return {
            //当前活动页
            activeWindowId: activeWindowId,
            pages: pages,
            url: urlAddress
        }
    }
}

module.exports = ViewManager;
